//
//  TRSendViewController.m
//  WeiMiLan
//
//  Created by Mac on 14-7-19.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRSendViewController.h"
#import "KYAlbumViewController.h"

@interface TRSendViewController ()<UITextViewDelegate,albumDelegate,ZYQAssetPickerControllerDelegate>
@property (nonatomic, strong) UIImagePickerController *imagePickerController;
@property (strong,nonatomic)NSMutableArray *images;
@property (weak, nonatomic) IBOutlet UIButton *addBtn;
@property (strong,nonatomic)NSArray *directorys;
@property (strong, nonatomic) IBOutlet UIPickerView *directoryPicker;
@property (weak, nonatomic) IBOutlet UIView *directoryBg;
@property (strong,nonatomic)NSString *directoryString;
@property (weak, nonatomic) IBOutlet UILabel *placeHolderLabel;
@property (nonatomic)int j;
@property (weak, nonatomic) IBOutlet UIView *operationView;

@property(nonatomic,assign)CGPoint oldOffset;
@property(nonatomic,assign)CGFloat yValue;

@property(nonatomic,assign)NSInteger timeCount;

@property(copy,nonatomic)NSString * timeString;
@end

@implementation TRSendViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)textViewDidChange:(UITextView *)textView
{
    //    self.examineText =  textView.text;
    if (textView.text.length == 0) {
        
        self.placeHolderLabel.text = @"请务必填写品牌名称";
    }else{
        self.placeHolderLabel.text = @"";
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    for (UIView* v in self.operationView.subviews) {
        if ([v isMemberOfClass:[UITextField class]]) {
            
            v.layer.borderColor = [UIColor colorWithRed:203/255. green:155/255. blue:15/255. alpha:1].CGColor;
            v.layer.borderWidth = 1.f;
            v.layer.cornerRadius = 5.f;
            v.layer.masksToBounds = YES;
            ((UITextField *)v).font = [UIFont systemFontOfSize:16.f];
            ((UITextField *)v).textColor = [UIColor whiteColor];
            [v setValue:[UIColor colorWithRed:92/255. green:92/255. blue:92/255. alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
            [v setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
            
            v.backgroundColor = [UIColor colorWithRed:44/255. green:44/255. blue:44/255. alpha:1];
        }
        
        if ([v isMemberOfClass:[UITextView class]]) {
            
            v.layer.borderColor = [UIColor colorWithRed:203/255. green:155/255. blue:15/255. alpha:1].CGColor;
            
            ((UITextView *)v).font = [UIFont systemFontOfSize:16.f];
            ((UITextView *)v).textColor = [UIColor whiteColor];
            self.placeHolderLabel.textColor = [UIColor colorWithRed:92/255. green:92/255. blue:92/255. alpha:1];
            self.placeHolderLabel.font =[UIFont boldSystemFontOfSize:16];
            v.backgroundColor = [UIColor colorWithRed:44/255. green:44/255. blue:44/255. alpha:1];
        }
    }
    
    
    self.scrollView.contentSize=CGSizeMake(kUI_SCREEN_WIDTH, kUI_SCREEN_HEIGHT+200);
    self.scrollView.contentOffset=CGPointMake(0, 0);
    self.backgroundImage.layer.borderWidth=1.5f;
    self.backgroundImage.layer.cornerRadius=5.0f;
    self.backgroundImage.layer.borderColor=[[UIColor colorWithRed:142/225.0 green:28/255.0 blue:130/255.0 alpha:1] CGColor];
    
    //self.scrollView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"main_bg"]];
    self.scrollView.backgroundColor=[UIColor whiteColor];
    self.images=[NSMutableArray array];
    [self initNavigation];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveMessage:) name:SERVICE_NAME_DIRECTORY object:nil];
    
    self.yValue = 100;
    self.directorys=@[@{@"ID":@"2219",@"NAME":@"服装"},@{@"ID":@"2218",@"NAME":@"包包"},@{@"ID":@"2217",@"NAME":@"丝巾"},@{@"ID":@"2216",@"NAME":@"手表"},@{@"ID":@"2215",@"NAME":@"鞋子"},@{@"ID":@"2214",@"NAME":@"眼镜"},@{@"ID":@"2213",@"NAME":@"皮带"},@{@"ID":@"2212",@"NAME":@"钱夹"},@{@"ID":@"2211",@"NAME":@"饰品"}];
    
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.oldOffset = self.scrollView.contentOffset;
    self.imageNum=1;
}

-(void)receiveMessage:(NSNotification*)nofi
{
    
    self.directorys=nofi.userInfo[@"BODY"][@"PACKAGE_RSP"][@"PACKAGE"];
    
    
    [self.directoryPicker reloadAllComponents];
    
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"";
    [self.weChatNavigationBar.rightButton setImage:nil forState:0];
    [self.weChatNavigationBar .leftButton addTarget:self action:@selector(exit)  forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.rightButton.hidden=NO;
    self.weChatNavigationBar.rightButton.frame=CGRectMake(kUI_SCREEN_WIDTH-80, 20, 54, 44);
    [self.weChatNavigationBar.rightButton setImage:[UIImage imageNamed:@"上传按钮"] forState:0];
    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)exit
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)delImageFromArray:(NSArray *)array{
    
    [self.images removeAllObjects];
    [self.images addObjectsFromArray:array];
    
    
    for (UIView* v in self.backgroundImage.subviews) {
        if ([v isMemberOfClass:[UIImageView class]]) {
            [v removeFromSuperview];
        }
    }
    
    [self updateImagesfrom:self.images];
}

//现在照片
- (IBAction)chooseImages:(UIButton *)sender
{
    if (self.images.count>=9) {
        [SVProgressHUD showImage:nil status:@"最多不超过9张"];
        return;
    }
    [self pickAssets:nil];
    
}
- (void)pickAssets:(id)sender
{
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 9;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups=NO;
    picker.delegate=self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    
    [self presentViewController:picker animated:YES completion:NULL];
}


#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    for (int i=0; i<assets.count; i++) {
        ALAsset *asset=assets[i];
        NSString *fileName = asset.defaultRepresentation.filename;
        UIImage *image=[UIImage imageWithCGImage:asset.defaultRepresentation.fullResolutionImage];
        if (self.images.count<9) {
            [self.images addObject:@{@"image": image,@"name":fileName}];
        }else{
            [SVProgressHUD showImage:nil status:@"最多不超过9张"];
        }
    }
    _j=0;
    [self updateImagesfrom:self.images];
    //还原
    self.imageNum=1;
}

- (void)updateImagesfrom:(NSArray *)images
{
    
    for (int i=0; i<images.count; i++) {
        UIImageView *iv=[[UIImageView alloc] init];
        
        iv.userInteractionEnabled = YES;
        iv.tag = i+1;
        
        int x=i%4*80;
        int y=i/4*80;
        iv.frame=CGRectMake(x,y, 75, 75);
        iv.image=images[i][@"image"];
        self.backgroundImage.userInteractionEnabled = YES;
        [self.backgroundImage addSubview:iv];
        //加点击手势
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(delAndLookImage)];
        [iv addGestureRecognizer:tap];
        
        
    }
    if (images.count>=9) {
        self.backgroundImage.height=80*3;
        //操作view下移80
        self.operationView.top=242+80;
        self.yValue = 100+80;
        self.addBtn.top = 190+80;
    }
    
    
}

-(void)delAndLookImage{
    KYAlbumViewController * vc = [[KYAlbumViewController alloc]init];
    vc.album = self.images;
    vc.isFromGood = NO;
    vc.delegate = self;
    
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    
    if ([textField isEqual:self.DirectoryTextField]) {
        [self.contentTextView resignFirstResponder];
        [self.priceTF resignFirstResponder];
        self.directoryBg.hidden = NO;
        [self.scrollView setContentOffset:CGPointFromString([NSString stringWithFormat:@"{0,%f}",self.yValue]) animated:YES];
        if (self.directorys.count==0) {
            [self getDirectorys];
        }
        
        return NO;
    }
    
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    return YES;
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    [self.scrollView setContentOffset:CGPointFromString([NSString stringWithFormat:@"{0,%f}",self.yValue]) animated:YES];
    return YES;
}


-(void)getDirectorys
{
    
    //  NSString *  s=[ApplicationDelegate.udpClientSocket
    //                 createXmlDirectoryUserName:ApplicationDelegate.userName
    //                 orderField:DIR_ORDER_FIELD_CREATEDATE
    //                 orderDirection:DIR_ORDER_DIRECTION_ASC
    //                 ids:nil
    //                 brandIds:nil
    //                 pageNum:@"1"
    //                 serviceName:SERVICE_NAME_DIRECTORY
    //                 serviceType:SERVICE_TYPE_DIRECTORY
    //                 serviceCode:@"1008"];
    //    [ApplicationDelegate.udpClientSocket sendMessage:s];
}


//创建一条本地通知
-(void)createLocalNofi{
    UILocalNotification *notification=[[UILocalNotification alloc] init];
    if (notification!=nil) {
        NSDate *now=[NSDate new];
        notification.fireDate=[now dateByAddingTimeInterval:2];//10秒后通知
        notification.repeatInterval=0;//循环次数，kCFCalendarUnitWeekday一周一次
        notification.timeZone=[NSTimeZone defaultTimeZone];
        notification.applicationIconBadgeNumber=1; //应用的红色数字
        notification.soundName= UILocalNotificationDefaultSoundName;//声音，可以换成alarm.soundName = @"myMusic.caf"
        //去掉下面2行就不会弹出提示框
        notification.alertBody=@"正在上传商品";//提示信息 弹出提示框
        notification.alertAction = @"打开";  //提示框按钮
        //notification.hasAction = NO; //是否显示额外的按钮，为no时alertAction消失
        
        NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
        notification.userInfo = infoDict; //添加额外的信息
        
        //立即触发一个通知
        [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
    }
}

#pragma mark pinkerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.directorys.count;
    
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    
    return 50;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *myView = nil;
    
    
    myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 55)];
    
    myView.textAlignment = NSTextAlignmentCenter;
    
    myView.text = self.directorys[row][@"NAME"];
    
    
    myView.textColor=[UIColor whiteColor];
    
    myView.font = [UIFont systemFontOfSize:22];         //用label来设置字体大小
    
    myView.backgroundColor = [UIColor clearColor];
    
    return myView;
    
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    self.DirectoryTextField.text=self.directorys[row][@"NAME"];
    self.directoryString=self.directorys[row][@"ID"];
    //    self.directoryPicker.hidden=YES;
    self.directoryBg.hidden = YES;
    [self.scrollView setContentOffset:self.oldOffset animated:YES];
}

-(int)getRandomNumber:(int)from to:(int)to

{
    return (int)(from + (arc4random() % (to - from + 1)));
}

- (IBAction)sendAction:(UIButton *)sender
{
    
    //如果在上传中，不允许点击
    if (ApplicationDelegate.upDataLoadingBtn) {
        [SVProgressHUD showErrorWithStatus:@"正在上传中，请稍后…"];
        return;
    }
    
    if (self.images.count==0) {
        [SVProgressHUD showErrorWithStatus:@"请选择图片"];
        return;
    }
    
    if (self.DirectoryTextField.text.length<1) {
      //  [SVProgressHUD showErrorWithStatus:@"请输入商品目录"];
        return;
    }
    
//    if (self.priceTF.text.length<1) {
//        [SVProgressHUD showErrorWithStatus:@"请输入商品价格"];
//        return;
//    }
    
    self.timeString=[CurrentDate getCurrentTimeString];
    NSMutableDictionary * paramDict = [@{}mutableCopy];
    NSMutableArray * arr = [@[]mutableCopy];
    NSMutableArray * nameArr = [@[]mutableCopy];
    for (int i=0; i<self.images.count; i++) {
        NSDictionary *dict=self.images[i];
        [arr addObject:dict[@"image"]];
        [nameArr addObject:dict[@"name"]];
        
    }
    
    
    ApplicationDelegate.sendImageDict =  @{@"contentTextView":self.contentTextView.text,
                                           @"nameTextField":@"",
                                           @"directoryString":self.directoryString,
                                           
                                           };
    
    [paramDict setObject:self.contentTextView.text forKey:@"description"];
    NSString *productName = [[NSDate date] ql_ToStringWithFormat:@"yyyyMMdd_HHmmss"];
    [paramDict setObject:[NSString stringWithFormat:@"%@__%d",productName,[self getRandomNumber:1 to:10000]] forKey:@"productName"];
    [paramDict setObject:self.directoryString forKey:@"pkgId"];
    [paramDict setObject:[NSNumber numberWithInt:[self.priceTF.text intValue]] forKey:@"price"];
    [paramDict setObject:arr forKey:@"imageArray"];
    [paramDict setObject:self.timeString forKey: @"createDate"];
    
    //发送到后台
    [ApplicationDelegate sendImageWithImage:paramDict andName:nameArr];
    
    //处理现场
    self.imageNum=1;
    
    //    self.DirectoryTextField.text=@"";
    self.contentTextView.text=@"";
    self.placeHolderLabel.text = @"请务必填写品牌名称";
    for (UIView *v in self.backgroundImage.subviews) {
        [v removeFromSuperview];
    }
    self.images=[NSMutableArray array];
}

- (IBAction)tapAction:(UITapGestureRecognizer *)sender
{
    [self.contentTextView resignFirstResponder];
    [self.DirectoryTextField resignFirstResponder];
    [self.priceTF resignFirstResponder];
    
    [self.scrollView setContentOffset:self.oldOffset animated:YES];
    //    self.directoryPicker.hidden=YES;
    self.directoryBg.hidden = YES;
}

- (IBAction)houToSend:(UIButton *)sender
{
    
    // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.vsmu.cn/sc.html"]];
}

@end
